import { computed, unref, ref, watch } from 'vue';
import type { Ref } from 'vue';

export interface PaginationProps {
  current?: number;
  pageSize?: number;
  total: number;
}

export function usePagination(paginationRef: Ref<PaginationProps>) {
  const configRef = ref<PaginationProps>({ total: 0 });

  watch(
    () => unref(paginationRef),
    (pagination) => {
      configRef.value = {
        ...unref(configRef),
        ...(pagination ?? {}),
      };
    },
  );

  const getPaginationInfo = computed((): PaginationProps => {
    const pagination = unref(paginationRef);

    return {
      current: 1,
      pageSize: 5,
      ...pagination,
      ...unref(configRef),
    };
  });

  function setPagination(info: Partial<PaginationProps>) {
    const paginationInfo = unref(getPaginationInfo);
    configRef.value = {
      ...paginationInfo,
      ...info,
    };
  }

  function getPagination() {
    return unref(getPaginationInfo);
  }

  return { getPagination, getPaginationInfo, setPagination };
}
